package OnlineLibrary.managers;

import java.util.ArrayList;

import org.omg.CosNaming.NameComponent;

import BookStore.common.Book;
import BookStore.managers.CatalogBookStoreMgr_Iface.CatalogBookStoreMgr;
import BookStore.managers.CatalogBookStoreMgr_Iface.CatalogBookStoreMgrHelper;

/**
 * Manages the catalog of online library by merging the catalog of each book store
 * @author Loup
 *
 */
public class CatalogMgr extends Mgr {
	private CatalogBookStoreMgr[] catalogs;

	public CatalogMgr() {
		super();

		this.catalogs = new CatalogBookStoreMgr[ids.length];

		// call all catalog servants

		for (int i = 0; i < this.ids.length; i++) {
			String id = this.ids[i];
			NameComponent[] name = new NameComponent[] { new NameComponent(
					"Catalog", "Object" + id) };
			try {
				catalogs[i] = CatalogBookStoreMgrHelper.narrow(context
						.resolve(name));
			} catch (Exception e) {
				System.out.println("null");
				catalogs[i] = null;
			}
		}

	}

	/**
	 * 
	 * @return The union of the book store catalogs
	 */
	private ArrayList<Book> getCatalogs() {
		ArrayList<Book> catalogs = new ArrayList<Book>();
		for (int i = 0; i < this.catalogs.length; i++) {
			if (this.catalogs[i] != null) {
				try {
					Book[] list = this.catalogs[i].askCatalog();
					for (Book b : list) {
						catalogs.add(b);
					}
				} catch (Exception e) {
					// store not connected
				}
			}
		}
		return catalogs;
	}

	/**
	 * 
	 * @return The union of each book store catalog. Each book appears only once
	 */
	public ArrayList<Book> mergeCatalogs() {
		ArrayList<Book> allCatalogs = getCatalogs();
		for (int i = 0; i < allCatalogs.size(); i++) {
			Book b = allCatalogs.get(i);
			float max = b.sell_price;
			for (int j = i + 1; j < allCatalogs.size(); j++) {
				if (allCatalogs.get(j).isbn.equals(b.isbn)) {
					if (allCatalogs.get(j).sell_price > max)
						max = allCatalogs.get(j).sell_price;
					allCatalogs.remove(j);
					j--;
				}
			}
			b.sell_price = max;
			allCatalogs.set(i, b);
		}
		return allCatalogs;
	}

}
